import { useState } from 'react'
import { Pressable } from 'react-native'
import { createStyles, useStyles } from '@mf2e/react-native-theme-styles'

const BaseBtn = ({ style, children, onPress, loadingStyle, loadingComponent, ...otherProps }) => {
  const styles = useStyles(themeStyles)

  const [loading, setLoading] = useState(false)

  const onAsyncPress = async (e) => {
    if (loading) return

    setLoading(true)
    try {
      await onPress?.(e)
    } catch (err) {
      console.log(err)
    }
    setLoading(false)
  }

  return (
    <Pressable
      style={[style, loading && !loadingComponent && (loadingStyle || styles.loading)]}
      onPress={onAsyncPress}
      {...otherProps}
    >
      {loading && loadingComponent ? loadingComponent : children}
    </Pressable>
  )
}

const themeStyles = createStyles({
  loading: {
    opacity: 0.3,
  },
})

export default BaseBtn
